package cn.edu.swu.mhans.agent;

import cn.edu.swu.mhans.common.player.AbstractNegotiationAgentPlayer;
import cn.edu.swu.mhans.common.player.NegotiationCommand;
import cn.edu.swu.mhans.common.util.ApplicationContextProvider;
import cn.edu.swu.mhans.common.util.IdUtils;
import cn.edu.swu.mhans.game.constants.NormalCommandType;
import cn.edu.swu.mhans.room.demo.issue.DiscreteIssue;
import cn.edu.swu.mhans.room.demo.role.PlayerPreferences;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.amqp.core.AmqpTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 一个简单的示例agent
 *
 * @author ZhanJingbo
 * @version 1.0.0
 * Created on 2018/5/2
 */
public class SimpleAgent extends AbstractNegotiationAgentPlayer {


    private final String QUEUE_NAME = "normalGame";

    private PlayerPreferences playerPreferences;

    private List<DiscreteIssue> issueList;

    public SimpleAgent() {
        this.setAgentId(IdUtils.getRandomIdString());
    }

    /**
     * 处理传输来的数据
     *
     * @param negotiationCommand 待处理的数据
     */
    @Override
    public void handleNegotiationCommand(NegotiationCommand negotiationCommand) {
        NormalCommandType commandType = NormalCommandType.getCommandType(negotiationCommand.getCommandType());
        if (null == commandType) {
            return;
        }
        // 命令处理
        switch (commandType) {
            case CHAT_MESSAGE:
                handleChatMessage(negotiationCommand);
                break;
            case ALLOC_ROLE:
                handleAllocRole(negotiationCommand);
                break;
            case CHOOSE_MC:
                handleChooseMc(negotiationCommand);
                break;
            case VOTE:
                handleVote(negotiationCommand);
                break;
            case GAME_OVER:
                handleGameOver(negotiationCommand);
                break;
            default:
                break;
        }
    }

    /**
     * 处理游戏结束
     *
     * @param negotiationCommand 操作对象
     */
    private void handleGameOver(NegotiationCommand negotiationCommand) {
    }

    /**
     * 根据出价进行表决
     *
     * @param negotiationCommand 操作对象
     */
    private void handleVote(NegotiationCommand negotiationCommand) {
        NegotiationCommand returnCommand = new NegotiationCommand(NormalCommandType.PLAYER_VOTE.getValue(), negotiationCommand.getRoomId());
        returnCommand.setFromNegotiationPlayerId(getNegotiationPlayerId());
        Map<String, Object> data = Maps.newHashMap();
        // 示例Agent永远选择同意
        data.put("voteResult", true);
        returnCommand.setData(data);
        sentNegotiationCommandToMessageQueue(returnCommand);
    }

    /**
     * 出价
     */
    private void handleChooseMc(NegotiationCommand command) {
        if (!command.getData().get("mcId").equals(getNegotiationPlayerId())) {
            return;
        }

        Map<String, Object> data = Maps.newHashMap();
        for (DiscreteIssue issue : issueList) {
            data.put(issue.getName(), issue.getOptions().get(0).getName());
        }
        NegotiationCommand returnCommand = new NegotiationCommand(NormalCommandType.MC_OFFER.getValue(), command.getRoomId());
        returnCommand.setFromNegotiationPlayerId(getNegotiationPlayerId());
        returnCommand.setData(data);
        sentNegotiationCommandToMessageQueue(returnCommand);
    }

    /**
     * 收到聊天消息的通知
     *
     * @param command
     */
    private void handleChatMessage(NegotiationCommand command) {
        NegotiationCommand returnCommand = new NegotiationCommand(NormalCommandType.CHAT_MESSAGE.getValue(), command.getRoomId());
        returnCommand.setFromNegotiationPlayerId(getNegotiationPlayerId());

        Map<String, Object> data = new HashMap<>();
        data.put("fromPlayerName", getNegotiationPlayerName());
        data.put("chatMessage", "你们在聊些什么？我听不懂。");
        returnCommand.setData(data);

        sentNegotiationCommandToMessageQueue(returnCommand);
    }

    /**
     * 游戏开始 信息初始化
     *
     * @param command 操作对象
     */
    private void handleAllocRole(NegotiationCommand command) {
        this.playerPreferences = (PlayerPreferences) command.getData().get("role");
        this.issueList = (List<DiscreteIssue>) command.getData().get("issueList");
    }

    private void sentNegotiationCommandToMessageQueue(NegotiationCommand command) {
        try {
            Thread.sleep(300);
            ObjectMapper mapper = new ObjectMapper();
            getAmqpTemplate().convertAndSend(QUEUE_NAME, mapper.writeValueAsString(command));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private AmqpTemplate getAmqpTemplate() {
        return ApplicationContextProvider.getBean(AmqpTemplate.class);
    }
}
